package com.qire.common.model.entity;

import com.qire.common.basic.DateUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.constant.CacheStorageKey;
import com.qire.common.constant.TeensModeManage;
import com.qire.common.model.enumeration.LoginChannelType;
import com.qire.common.model.enumeration.VIPType;
import com.qire.common.utils.CacheStorageUtil;
import com.qire.common.utils.OkGoConfigHelper;
import com.qire.other.push.PushManage;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户实例（单利，APP同时只会有一个用户）
 */
public class UserEntity {

    public static final UserEntity self = new UserEntity();

    private UserEntity(){}

    // region #用户属性字段
    /** 登录口令token*/
    private String   token = "";
    /** 登录渠道*/
    private LoginChannelType loginChannel;
    /** 用户ID*/
    private int      id;
    /** 用户昵称*/
    private String   name;
    /** 用户头像*/
    private String   portrait;
    /** 用户性别  女:0 男:1 未知:-1*/
    private String   sex;
    /** 用户生日*/
    private String   birthday;
    /** 用户所在市*/
    private City     city;
    /** 用户所在省*/
    private City     province;
    /** 用户电话*/
    private String   mobile;
    /** 用户微信昵称*/
    private String   weChatName;
    /** 用户QQ昵称*/
    private String   qqName;
    /** VIP类型          : 0 非会员 1 会员*/
    private VIPType  vipType;
    /** 会员过期时间      : 2019-08-01 14:00:00*/
    private String   vipExpirationTime;
    /** 未读消息数 */
    private int messageCount;
    /** 未处理任务数 */
    private int taskCount;
    /** 未领取奖励任务数 */
    private int taskRewardCount;






    /** 是否是测试号      : 0否 1是*/
    private boolean  isTest;
    /** 是否被禁用        : 0否 1是*/
    private boolean  isForbidden;
    /** 是否是游客        : 0否 1是*/
    private boolean  isVisitor;
    /** 是否开启自动支付   : 0否 1是*/
    private boolean  isAutoPay;
    /** 是否在应用商店评价 : 0否 1是*/
    private boolean  isEva;

    /**
     * 金币余额，并非用户基础数据需要通过account账户接口来同步：Url.account_index
     */
    private float coinBalance = 0;
    /**
     * 金豆余额，并非用户基础数据需要通过account账户接口来同步：Url.account_index
     */
    private float beanBalance = 0;

    /**
     * 今日剩余广告解锁次数
     */
    private int canAdUnlockedCount = 0;

    /**
     * 是否开启偏好收集
     */
    private boolean enablePreferences = true;
    // endregion

    // region #用户属性字段get/set
    public void setToken(String token) {
        this.token = token;
        // 更新ToKen
        OkGoConfigHelper.refreshToken();
    }

    public void setLoginChannel(LoginChannelType loginChannelType) {
        this.loginChannel = loginChannelType;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPortrait(String portrait) {
        this.portrait = portrait;
    }

    public void setSex(int sexValue) {
        if(sexValue == -1) {
            setSex("未设置");
            return;
        }
        setSex(sexValue == 1);
    }
    public void setSex(boolean isMale) {
        setSex(isMale ? "男" : "女");
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public void setCityInfo(int cityId, String cityName, String provinceName) {
        setCity(new City(cityId, cityName));
        setProvince(new City((cityId / 1000) * 1000, provinceName));
    }

    public void setCity(City city) {
        this.city = city;
    }

    public void setProvince(City province) {
        this.province = province;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public void setWeChatName(String weChatName) {
        this.weChatName = weChatName;
    }

    public void setQqName(String qqName) {
        this.qqName = qqName;
    }

    public void setVipType(int vipType) {
        setVipType(VIPType.build(vipType));
    }
    public void setVipType(VIPType vipType) {
        this.vipType = vipType;
    }
    public void setVipExpirationTime(String vipExpirationTime) {
        this.vipExpirationTime = vipExpirationTime;
    }

    public void setMessageCount(int messageCount) {
        this.messageCount = messageCount;
    }

    public void setTaskCount(int taskCount) {
        this.taskCount = taskCount;
    }

    public void setTaskRewardCount(int taskRewardCount) {
        this.taskRewardCount = taskRewardCount;
    }



    public void setTest(int testValue) {
        setTest(testValue == 1);
    }
    public void setTest(boolean test) {
        isTest = test;
    }

    public void setForbidden(int forbidden) {
        setForbidden(forbidden == 1);
    }
    public void setForbidden(boolean forbidden) {
        isForbidden = forbidden;
    }

    public void setVisitor(int visitor) {
        setVisitor(visitor == 1);
    }
    public void setVisitor(boolean visitor) {
        isVisitor = visitor;
    }

    public void setAutoPay(int autoPay) {
        setAutoPay(autoPay == 1);
    }
    public void setAutoPay(boolean autoPay) {
        isAutoPay = autoPay;
    }

    public void setEva(int eva) {
        setEva(eva == 1);
    }
    public void setEva(boolean eva) {
        isEva = eva;
    }

    public void setCoinBalance(float coinBalance) {
        this.coinBalance = coinBalance;
    }

    public void setBeanBalance(float beanBalance) {
        this.beanBalance = beanBalance;
    }

    public void setCanAdUnlockedCount(int canAdUnlockedCount) {
        this.canAdUnlockedCount = canAdUnlockedCount;
    }

    public void setEnablePreferences(boolean enablePreferences) {
        this.enablePreferences = enablePreferences;
    }


    public String getToken() {
        return token;
    }

    public LoginChannelType getLoginChannel() {
        return loginChannel;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        if(name == null) {
            return "";
        }
        return name;
    }

    public String getPortrait() {
        return portrait;
    }

    public int getSexValue() {
        if("男".equals(sex)) {
            return 1;
        }
        if("女".equals(sex)) {
            return 0;
        }
        return -1;
    }
    public String getSex() {
        return sex;
    }

    public String getBirthday() {
        return birthday;
    }

    public City getCity() {
        if(city == null) {
            return new City(0, "");
        }
        return city;
    }

    public City getProvince() {
        if(province == null) {
            return new City(0, "");
        }
        return province;
    }

    public String getMobile() {
        return mobile;
    }

    public String getWeChatName() {
        return weChatName;
    }
    public boolean isNotBindWeChat() {
        return StringUtil.isEmpty(weChatName);
    }

    public String getQqName() {
        return qqName;
    }

    public VIPType getVipType() {
        if(vipType == null) {
            return VIPType.NONE;
        }
        return vipType;
    }

    public String getVipExpirationTime() {
        return vipExpirationTime;
    }

    public String getShortVipExpirationTime() {
        if(vipExpirationTime == null) {
            return "";
        }
        return DateUtil.yMdHms.to(vipExpirationTime, DateUtil.yMd);
    }

    public int getMessageCount() {
        return messageCount;
    }

    public int getTaskCount() {
        return taskCount;
    }

    public int getTaskRewardCount() {
        return taskRewardCount;
    }

    public boolean isTest() {
        return isTest;
    }

    public boolean isForbidden() {
        return isForbidden;
    }

    public boolean isVisitor() {
        return isVisitor;
    }

    public boolean isAutoPay() {
        if(!isLogin()) {
            return false;
        }
        return isAutoPay;
    }

    public boolean isEva() {
        return isEva;
    }

    /**
     * 是否设置昵称
     * @return 昵称不为空且不为手机号码则返回 true， 否则返回 false
     */
    public boolean haveNickname() {
        return StringUtil.notEmpty(name) && !StringUtil.isMobile(name.replace("*", "0"));
    }

    /**
     * 可以用于支付的余额
     * */
    public float getCanPayBalance() {
        return this.coinBalance + this.beanBalance;
    }

    public float getCoinBalance() {
        return this.coinBalance;
    }

    public float getBeanBalance() {
        return this.beanBalance;
    }

    public int getCanAdUnlockedCount() {
        return canAdUnlockedCount;
    }

    public boolean getEnablePreferences() {
        if(!isLogin()) {
            return false;
        }
        return enablePreferences;
    }

    public boolean canAdUnlocked() {
        return getCanAdUnlockedCount() > 0;
    }

    public boolean isLogin() {
        return StringUtil.notEmpty(getToken());
    }

    public boolean isVip() {
        if(!isLogin()) {
            return false;
        }
        return vipType != VIPType.NONE;
    }

    public boolean isIllegalName() {
        Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]|[~#@*+%{}<>\\[\\]|\"\\_^]");///^[\x{4e00}-\x{9fa5}A-Za-z0-9]+$/u
        Matcher matcher = pattern.matcher(this.name);
        return matcher.find();
    }

    public boolean haveBindMobile() {
        return StringUtil.notEmpty(mobile);
    }
    // endregion


    // region #用户属性用于展示文本
    public CharSequence idToText() {
        return String.valueOf(id);
    }
    public CharSequence nicknameToText() {
        if(haveNickname()) {
            return getName();
        }
        return "未设置";
    }
    public CharSequence sexToText() {
        if(StringUtil.isEmpty(sex)) {
            return "未设置";
        }
        return sex;
    }
    public CharSequence birthdayToText() {
        if(StringUtil.isEmpty(birthday)) {
            return "未设置";
        }
        if("0000-00-00".equals(birthday)) {
            return "未设置";
        }
        return birthday;
    }
    public CharSequence cityToText() {
        String cityText = (getProvince().name + " " + getCity().name).trim();
        return StringUtil.isEmpty(cityText) ? "未设置" : cityText;
    }
    // endregion

    public void loadLocalUserInfo() {
        UserEntity user = CacheStorageUtil.query(CacheStorageKey.SAVE_USER, UserEntity.class);

        if(user != null) {
            this.token       = user.token;
            this.id          = user.id;
            this.name        = user.name;
            this.portrait    = user.portrait;
            this.sex         = user.sex;
            this.birthday    = user.birthday;
            this.city        = user.city;
            this.province    = user.province;
            this.mobile      = user.mobile;
            this.weChatName  = user.weChatName;
            this.qqName      = user.qqName;
            this.vipType     = user.vipType;
            this.isTest      = user.isTest;
            this.isForbidden = user.isForbidden;
            this.isVisitor   = user.isVisitor;
            this.isAutoPay   = user.isAutoPay;
            this.isEva       = user.isEva;
            this.enablePreferences = user.enablePreferences;
        }
    }

    /**
     * 更新推送别名
     */
    public void updatePushAlias() {
        if(isLogin()) {
            PushManage.setAliasToPush(id);
        }
    }

    /**
     * 登录
     * */
    public void login(int userId, String token) {
        setId(userId);
        setToken(token);
        save();
        updatePushAlias();
    }

    /**
     * 退出登录
     * */
    public void logout() {
        setToken("");
        setName("");
        setPortrait("");
        setMobile("");
        setMessageCount(0);
        setTaskCount(0);
        setTaskRewardCount(0);
        setCoinBalance(0);
        setBeanBalance(0);
        save();
        TeensModeManage.updateTeensModeEnable(false);
    }

    /**
     * 保存缓存
     * */
    public void save() {
        CacheStorageUtil.save(CacheStorageKey.SAVE_USER, this);
    }

}
